<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use Auth;
use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\SuperAgent;
use App\Agent;
use App\PublicGemsLog;
use App\Club;
use App\ClubUser;
use App\Withdraw;
use App\PhoneValidate;

class SuperAgentController extends Controller
{
    protected $config = [
        'debug' => true,
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',
        'token' => '',
    ];

	/**
	 * [index description]
	 * @return [type] [description]
	 */
	public function index()
	{
		$agent = Auth::guard('agent')->user();
		return view('mobile.superagent.index', compact('agent'));
	}

	/**
	 * [dvlp description]
	 * @return [type] [description]
	 */
	public function dvlp(SuperAgent $agent)
	{
		$title = "邀请代理";
       	$app = new Application($this->config);
        $js = $app->js;
		if (!file_exists(public_path()."/qrcode/superagent/superagent_$agent->id.jpg")) {
			$result = $app->qrcode->forever('superagent_'.$agent->id);
			$url = $app->qrcode->url($result['ticket']);
			$content = file_get_contents($url);
			file_put_contents(public_path() . "/qrcode/superagent/superagent_$agent->id.jpg", $content);
		}

		return view('mobile.superagent.share', compact('agent', 'title', 'js'));
	}

	/**
	 * [auditList description]
	 * @return [type] [description]
	 */
	public function auditList(SuperAgent $agent, Request $request)
	{
		$keywords = $request->input('keywords');
		$datas = Agent::where(['status' => 0, 'superagent_id' => $agent->id]);
		if ($keywords) {
			$datas = $datas->where(function($query) use ($keywords){
				$query->where('mobile', 'like', '%'.$keywords.'%')->orWhere('realname', 'like', '%'.$keywords.'%')->orWhere('nickname', 'like', '%'.$keywords.'%');
			});
		}
		$datas = $datas->get();
		return view('mobile.superagent.auditlist', compact('datas', 'agent'));
	}

	/**
	 * [doAudit description]
	 * @return [type] [description]
	 */
	public function doAudit(Agent $agent)
	{
		$my = Auth::guard('agent')->user();
		return view('mobile.superagent.doaudit', compact('agent', 'my'));
	}

	/**
	 * [storeAgent description]
	 * @return [type] [description]
	 */
	public function storeAudit(Request $request, Agent $agent)
	{
		$my = Auth::guard('agent')->user();
		if ($request->input('status') == 1) {
	    	$validator = Validator::make($request->input(), [
	            'divide' => 'required|min:1|max:100|numeric',
	        ],[
	        	'divide.required' => '分成比例不为空',
	        	'divide.min' => '分成比例大于1',
	        	'divide.max' => '分成比例小于100',
	        	'divide.numeric' => '分成比例为整数'
	        ]);
	        if ($request->input('divide') > $my->divide) {
	        	$validator->after(function($validator) use ($my){
    	            $validator->errors()->add('divide', '分成比例不能超过您可设置的最大上限: '.$my->divide);
    	        });
	        }
	    	if ($validator->passes()) {
	    		$agent->status = 1;
	    		$agent->divide = $request->input('divide');
	    		$agent->pass_time = time();
	    		$agent->save();
	    		$user = $agent->user();
	    		$user->agent = 1;
	    		$user->save();
        		/*自动创建俱乐部*/
        		$club = new Club;
        		$club->club_id = str_pad(mt_rand(1, 999999), 5, '0', STR_PAD_LEFT);
        		$club->club_name = base64_encode(base64_decode($user->name)."的亲友圈");
        		$club->creator = $user->userid;
        		$club->create_time = time();
        		$club->hotpush = 1;
        		$club->description = base64_decode($user->name)."的亲友圈";
        		$club->maxrooms = 5;
        		$club->club_fangfei = 0;
        		$club->limitpeople = 30;
        		$club->type = 1;
        		$club->save();
        		$club_user = new ClubUser;
        		$club_user->club_id = $club->club_id;
        		$club_user->userid = $user->userid;
        		$club_user->join_time = time();
        		$club_user->state = 999;
        		$club_user->save();

	            $app = new Application($this->config);
	            $notice = $app->notice;
	            $userService = $app->user;
	            $member = $userService->get($agent->open_id);
	            $subscribe = $member->subscribe;
	            if ($subscribe) {
		            $openId = $agent->open_id;
		            $templateId = 'q3kyGYoZalQ0fpCF57ipnMO__mwnoXLrZOSZOSQBjDY';
		            $url = url("/mobile/index");
		            $data = array(
		                "first" => "恭喜您通过了推广员审核，并为您开启了亲友圈!",
		                "keyword1" => "审核通过",
		                "keyword2" => "乐游手游一级推广员申请",
		                "keyword3" => date('Y-m-d H:i', $agent->shenqing_time),
		                "keyword4" => date('Y-m-d H:i', $agent->pass_time),
		                "remark" => "开启乐游之旅!",
		            );
		            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
		        }
	    		return redirect('/mobile/superagent/audit_list/'.$my->id);
	    	} else {
	    		return Redirect::back()->withInput()->withErrors($validator->errors());
	    	}	
		} else {
			$agent->status = 2;
			$agent->reject_reason = $request->input('reject_reason');
			$agent->save();
			return redirect('/mobile/superagent/audit_list/'.$my->id);
		}
	}

	/**
	 * [myson 我发展的一级代理]
	 * @return [type] [description]
	 */
	public function myson(SuperAgent $agent, Request $request)
	{
		$title = "我的代理";
		$keywords = $request->input('keywords');
		$users = Agent::where(['superagent_id' => $agent->id, 'status' => 1]);
		if ($keywords) {
			$users = $users->where(function($query) use ($keywords){
				$query->where('realname', 'like', '%'.$keywords.'%')->orWhere('mobile', 'like', '%'.$keywords.'%');
			});
		}
		$users = $users->orderBy('created_at', 'DESC')->get();

		return view('mobile.superagent.myson', compact('users', 'title', 'agent', 'keywords'));
	}

	/**
	 * [firstCard 给一级代理分配银票]
	 * @return [type] [description]
	 */
	public function firstCard(Agent $agent)
	{
		$my = Auth::guard('agent')->user();
		return view('mobile.superagent.firstcard', compact('agent', 'my'));
	}

	/**
	 * [storeFirstCard 给一级代理分配银票]
	 * @return [type] [description]
	 */
	public function storeFirstCard(Agent $agent, Request $request)
	{
        $validator = Validator::make($request->input(), [
            'gems' => 'required|numeric|min:1'
        ],[
        	'gems.required' => '请填写房卡数量',
        	'gems.numeric' => '房卡数量只能为整数',
        	'gems.min' => '房卡数量不少于1'
        ]);	
        $my = Auth::guard('agent')->user();
        if ($request->input('gems') > $my->gems) {
	        $validator->after(function($validator){
	            $validator->errors()->add('gems', '您的房卡不足!');
	        });
        }
        if ($validator->passes()) {
        	$my->gems -= $request->input('gems');
        	$agent_user = $agent->user();
        	$agent_user->gems += $request->input('gems');
        	$log = new PublicGemsLog;
        	$log->type = 11;
        	$log->send_id = $my->id;
        	$log->accept_id = $agent->id;
        	$log->gems = $request->input('gems');
			DB::beginTransaction();
	    	try{
	    		$my->save();
	    		$agent_user->save();
	    		$log->save();
	        	DB::commit();

	    		return redirect('/mobile/superagent/my_son/'.$my->id);
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		
	    		return redirect('/mobile/superagent/my_son/'.$my->id);	
	    	}
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
	}

	/**
	 * [firstLog description]
	 * @return [type] [description]
	 */
	public function firstLog(Agent $agent)
	{
    	$my = Auth::guard('agent')->user();
    	$logs = PublicGemsLog::where(['send_id' => $my->id, 'accept_id' => $agent->id, 'type' => 11])->orderBy('created_at', 'DESC')->get();
    	return view('mobile.superagent.firstlog', compact('logs'));
	}

	/**
	 * [editDivide description]
	 * @return [type] [description]
	 */
	public function editDivide(Agent $agent)
	{
		$my = Auth::guard('agent')->user();
		return view('mobile.superagent.editDivide', compact('agent', 'my'));
	}

	/**
	 * [storeDivide 修改分成比例]
	 * @return [type] [description]
	 */
	public function storeDivide(Agent $agent, Request $request)
	{
        $validator = Validator::make($request->input(), [
            'divide' => 'required|numeric|max:100|min:0'
        ],[
        	'divide.required' => '分成比例不能为空',
        	'divide.numeric' => '分成比列为整数',
        	'divide.min' => '分成比例不少于0',
        	'divide.max' => '分成比例不大于100'
        ]);
        $my = Auth::guard('agent')->user();
        if ($validator->passes()) {
        	$agent->divide = $request->input('divide');
        	$agent->save();

	    	return redirect('/mobile/superagent/my_son/'.$my->id);
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
	}	

	/**
	 * [openCircle 开启会员亲友圈]
	 * @return [type] [description]
	 */
	public function openCircle(Agent $agent)
	{
		$agent->open_circle = 1;
		$agent->save();
		return ['flag' => true];
	}

	/**
	 * 收入管理
	 */
	public function income(SuperAgent $agent)
	{
		return view('mobile.superagent.controlcash', compact('agent'));
	}

	/**
	 * 提现记录
	 */
	public function withdrawLog(SuperAgent $agent)
	{
		$datas = Withdraw::where(['agent_id' => $agent->id, 'is_super' => 1])->orderBy('created_at', 'DESC')->get();//提现记录
		return view('mobile.superagent.withdrawLog', compact('datas'));
	}

	/**
	 * 提现页面
	 */
	public function withdraw(SuperAgent $agent)
	{
		return view('mobile.superagent.withdraw', compact('agent'));
	}

	/**
	 * [doWithdraw description]
	 * @param  Request $request [description]
	 * @param  Agent   $agent   [description]
	 * @return [type]           [description]
	 */
	public function doWithdraw(Request $request, SuperAgent $agent)
	{
        $validator = Validator::make($request->input(), [
            'mobile' => 'required|regex:/^1[34578][0-9]{9}$/',
            'code' => 'required',
            'money' => 'required|numeric|min:100',
            'remark' => 'max:100'
        ],[
            'mobile.required' => '手机号不能为空!',
            'mobile.regex' => '手机号错误!',
            'code.required' => '请填写验证码!',
            'money.required' => '提现金额不为空!',
            'money.numeric' => '提现金额为数字!',
            'money.min' => '提现金额不少于100!',
            'remark.max' => '备注不要超过100字'
        ]);
        $exist = PhoneValidate::where('phone', '=', $request->input('mobile'))->where('code', '=', $request->input('code'))->first();
		if (!$exist) {
	        $validator->after(function($validator){
	            $validator->errors()->add('code', '验证码错误!');
	        });
		}
		if ($request->input('money') > $agent->money) {
        	$validator->after(function($validator){
	            $validator->errors()->add('money', '余额不足!');
	        });
		}
		if ($validator->passes()) {
			$withdraw = new Withdraw;
			$withdraw->agent_id = $agent->id;
			$withdraw->is_super = 1;
			$withdraw->money = $request->input('money');
			if ($request->input('remark')) {
				$withdraw->remark = $request->input('remark');
			}
			$agent->money -= $request->input('money');
			DB::beginTransaction();
	    	try{
	    		$withdraw->save();
	    		$agent->save();
	    		$exist->delete();
	        	DB::commit();

	        	return ['flag' => true];
	    	} catch (Exception $e) {
	    		DB::rollback();
	    		
	    		return back();
	    	}
		} else {
    		$errors = $validator->errors();
        	foreach ($errors->messages as $val) {
        		$error = $val[0];
        	}
        	return ['flag' => false, 'msg' => $error];	
		}	
	}

}	